package dev;

/**
 * ...
 * @author Cref
 */
using hxtc.Proxy;

class CimpleStore {
	public function new(server:cimple.remote.Reader,scope:EventScope, ?pollingInterval:Int) {
		this.server = server;
		this.scope = scope;
	}
	public var server(default,null):cimple.remote.Reader;
	public var pages(getPageReader, null):PageReader;
	public var scope(default, null):EventScope;
	dynamic function getPageReader():PageReader {
		var r = new PageReader(this);
		getPageReader = function() return r;
		return r;
	}
}

class PageReader {
	
	var pages:IntHash<Page>;
	var store:CimpleStore;
	public function new(store:CimpleStore) {
		this.store = store;
		pages = new IntHash();
		requestedPageIds = [];
		loadPagesDelayed=store.scope.delayed(loadPages, 100, true);
	}
	
	var requestedPageIds:Array<Int>;
	
	function loadPages() {
		store.server.getPageData(requestedPageIds).use(getPageDataCallback,false,true);
		requestedPageIds = [];
	}
	var loadPagesDelayed:Void->Void;
	
	function getPageDataCallback(s:String) {
		var pdata = s.split('\n');
		for (pdstr in pdata) {
			var pd = pdstr.split('\t');
			var p = pages.get(Std.parseInt(pd[0]));
			p.title.value = pd[1];
		}
	}
	
	public function get(id:Int):Page {
		var p = pages.get(id);
		if (p == null) {
			p = new Page(this, id);
			pages.set(id, p);
			requestedPageIds.push(id);
			loadPagesDelayed();
		}
		return p;
	}
	
}

class Page {
	
	public function new(reader:PageReader, id:Int) {
		this.reader = reader;
		this.id = id;
		title = new Property();
		exists = new Property();
	}
	
	public var id(default, null):Int;
	public var title(default, null):Property<String>;
	public var exists(default, null):Property<Bool>;
	var reader(default, null):PageReader;
}